<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <vxe-grid ref='materialOrderGrid' v-bind="gridOptions" class="my-grid66" @checkbox-all="selectAllChangeEvent1"
                @checkbox-change="selectChangeEvent1">
        <template #operate="{ row }">
          <a-space>
            <a class="ele-text-warning" @click="viewEvent(row)">查看</a>
            <a-divider type="vertical"/>
            <a class="ele-text-success" @click="inputOrder(row)">导入</a>
          </a-space>
        </template>

      </vxe-grid>
      <a-row :md="12" :sm="24" :xs="24">
        <a-form-item :wrapper-col="{md: {offset: 6}}" style="margin-bottom: -20px">
          <!--class="ele-pull-right"-->
          <div>
            <teleport to="#storeMaterialOrderInputModalFooter">
              <div>
                <a-space size="middle">
                  <a-button @click="storeMaterialListApp.orderInputShowing=false">取消
                  </a-button>
                  <a-button
                    type="primary"
                    @click="submitEvent()"
                    :loading="loading">导入
                  </a-button>
                </a-space>
              </div>
            </teleport>
          </div>
        </a-form-item>
      </a-row>


      <!--导入查看弹窗-->
      <vxe-modal v-model="storeMaterialListApp.orderInputDetailModalShowing" :title="gridOptions.showDetailsTitle"
                 id="materialOrderViewModal"
                 width="600"
                 min-width="460"
                 min-height="320"
                 :destroy-on-close="true"
                 :lock-view="false" :mask="false"
                 footer
                 show-footer show-zoom resize remember storage transfer dblclickZoom>
        <template #default>
          <StoreMaterialOrderInputDetail ref="storeMaterial-orderInputDetail"
                                         :orderId="storeMaterialListApp.currentId == null ? '0' : storeMaterialListApp.currentId"/>
        </template>
      </vxe-modal>
    </a-card>
  </div>
</template>

<script>
import {defineComponent, reactive, ref, toRefs, inject} from 'vue'//, Ref
import {VXETable} from 'vxe-table'//, VxeGridInstance, VxeGridProps
import {MaterialOrderService} from "@/views/restaurant/material/materialOrder/materialOrderService";
import StoreMaterialOrderInputDetail from "@/views/restaurant/material/storeMaterial/storeMaterial-orderInputDetail";
import {StoreMaterialService} from "@/views/restaurant/material/storeMaterial/storeMaterialService";

export default defineComponent({
  components: {
    StoreMaterialOrderInputDetail,
  },
  emits:['editClose'],
  setup(props,{emit}) {
    const materialOrderGrid = ref({})// as VxeGridInstance
    let proxyInfo = reactive({})
    const eid = ref({})
    const startIndex = ref({})
    const storeMaterialListApp = inject('storeMaterialListApp',{})
    const materialOrderListApp = inject('materialOrderListApp',{})
    const gridOptions = reactive({
      border: true,
      resizable: true,
      showHeaderOverflow: true,
      showOverflow: true,
      highlightHoverRow: true,
      keepSource: true,
      id: 'materialOrdersGrid',
      // maxHeight: "100%",//表格高度
      height: 800,
      rowId: 'eid',
      selectRow: null,
      showEdit: false,
      showDetails: false,
      showEditTitle: '新建',
      showDetailsTitle: '查看',
      formData: {},//自定义的
      detailData: [],
      startIndex: startIndex,
      printConfig: {
        columns: [
          {field: 'name'},
          {field: 'email'},
          {field: 'nickname'},
          {field: 'age'},
          {field: 'amount'}
        ]
      },
      /*TODO:排序配置 */
      sortConfig: {
        trigger: 'cell',
        remote: true,
        multiple: true,//多字段排序，默认单排序
        showIcon: true,
        // iconAsc: "fa fa-arrow-up fa-1x",
        // iconDesc: "fa fa-arrow-down fa-1x",
      },
      customConfig: {
        storage: true
      },
      /*TODO:过滤器配置*/
      filterConfig: {
        remote: true
      },
      /*TODO:分页配置*/
      pagerConfig: {
        pageSize: 10,
        pageSizes: [5, 10, 15, 20, 50]
      },
      /*TODO:请求代理配置*/
      proxyConfig: {
        seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
        sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
        filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
        form: false, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
        // 对应响应结果 { result: [], page: { total: 100 } }
        props: {
          result: 'data.datas', // 配置响应结果列表字段
          total: 'data.totalCount', // 配置响应结果总页数字段
          message: 'data.msg'
        },
        /*TODO:请求*/
        ajax: {
          /*TODO:分页条件查询*/
          query: ({page, sorts, filters}) => {  // 接收 Promise
            // const conditions = {...where.value}
            filters = {status: '待入库'}
            const queryParams = {}
            queryParams.currentPage = page.currentPage
            queryParams.pageSize = page.pageSize
            startIndex.value = (queryParams.currentPage - 1) * queryParams.pageSize + 1
            // 处理筛选条件
            queryParams.filters = filters;
            // // 处理排序条件
            queryParams.orderBys = sorts;
            //
            const $grid = materialOrderGrid.value

            $grid.queryParams = queryParams
            return MaterialOrderService.findMaterialOrders(queryParams).catch(error => {
              VXETable.modal.message({content: `加载数据出错，原因是：${error.message}`, status: 'error'});

            })
          },
        }
      },

      /*TODO:数据表列*/
      columns: [
        /*多选checkbox 单选seq*/
        {type: 'seq', title: '#', width: 40},
        {type: 'checkbox', field: 'eid', title: '订单编号', width: 100, sortable: true},

        {
          field: 'status',
          title: '订单状态',
          sortable: false
        },
        {
          field: 'price',
          title: '总价',
          sortable: false
        },
        {title: '操作', width: 250, slots: {default: 'operate'}}
      ],

      /*TODO:复选框配置*/
      checkboxConfig: {
        labelField: 'eid',
        reserve: false,
        highlight: false,
        range: true
      },
      /*TODO:编辑验证*/
      editRules: {
        name: [
          {required: true, message: 'app.body.valid.rName'},
          {min: 3, max: 50, message: '名称长度在 3 到 50 个字符'}
        ],
        email: [
          {required: true, message: '邮件必须填写'}
        ],
        role: [
          {required: true, message: '角色必须填写'}
        ]
      },
      editConfig: {
        trigger: 'click',
        mode: 'row',
        showStatus: true
      }
    })//as VxeGridProps
    /*TODO:新建事件*/
    const addEvent = () => {
      storeMaterialListApp.editModalShowing = true
      storeMaterialListApp.currentId = null;
      storeMaterialListApp.addModalForEdit = true;
      gridOptions.showEditTitle = "新建";
    }

    /*TODO:编辑事件*/
    const editEvent = (row) => {
      storeMaterialListApp.editModalShowing = true
      storeMaterialListApp.currentId = row.eid;
      storeMaterialListApp.editModalForEdit = true;
      gridOptions.showEditTitle = "编辑";
    }

    /*TODO:编辑关闭事件*/
    const editEventClose = () => {
      console.log(gridOptions.formData);
      VXETable.modal.message({content: '提交成功', status: 'success'})
    }

    /*TODO:查看事件*/
    const viewEvent = (row) => {
      storeMaterialListApp.currentId = row.eid;
      storeMaterialListApp.orderInputDetailModalShowing = true
      // gridOptions.showDetailsTitle = '查看';
    }

    const selectAllChangeEvent1 = ({checked}) => {
      const $table = materialOrderGrid.value
      const records = $table.getCheckboxRecords()
      console.log(checked ? '所有勾选事件' : '所有取消事件', records)
    }

    const selectChangeEvent1 = ({checked}) => {
      const $table = materialOrderGrid.value
      const records = $table.getCheckboxRecords()
      console.log(checked ? '勾选事件' : '取消事件', records)
    }

    const getSelectEvent1 = () => {
      const $table = materialOrderGrid.value
      const selectRecords = $table.getCheckboxRecords()
      return selectRecords
    }

    /*TODO:订单导入提交*/
    const submitEvent = () => {
      let selectedOrder = getSelectEvent1();
      console.log(selectedOrder)
      if (selectedOrder.length > 0) {
        console.log("可以入库")
        StoreMaterialService.updateStoreMaterialByOrder(selectedOrder).then(res => {
          console.log(res)
          storeMaterialListApp.orderInputShowing = false;
          emit('editClose',true)
          VXETable.modal.message({content: '入库成功', status: 'success'})
        })
      } else {
        VXETable.modal.message({content: "请至少选择一条订单入库", status: 'info'});
        console.log("请至少选择一条订单入库")
      }
    }

    /*TODO:单项订单导入*/
    const inputOrder = (row) => {
      let selectedOrder = [row];
      console.log(selectedOrder)
      StoreMaterialService.updateStoreMaterialByOrder(selectedOrder).then(res => {
        VXETable.modal.message({content: '入库成功', status: 'success'})
        const $table = materialOrderGrid.value
        $table.commitProxy('query')
        console.log(res)
      })

    }

    //TODO:这里需要返回才能调用
    return {
      eid,
      materialOrderGrid,
      gridOptions,
      materialOrderListApp,
      selectAllChangeEvent1,
      selectChangeEvent1,
      getSelectEvent1,
      addEvent,
      editEvent,
      submitEvent,
      viewEvent,
      editEventClose,
      inputOrder,
      storeMaterialListApp,
      ...toRefs(proxyInfo)
    }
  }
})
</script>

<style scoped>
.my-grid66 .alert-message {
  height: 40px;
  display: flex;
  align-items: center;
  margin: 10px 0;
  border-radius: 4px;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
}

.my-grid66 .alert-message-icon {
  width: 30px;
  text-align: center;
  color: #409eff;
  margin-right: 8px;
}

.my-grid66 .alert-message-content {
  flex-grow: 1;
  padding-right: 20px;
}

.my-grid66 .page-left {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
}

.my-grid66 .select-count {
  display: inline-block;
  vertical-align: middle;
}

.my-grid66 .my-input {
  width: 100%;
}

.my-grid66 .first-col {
  position: relative;
  height: 20px;
}

.my-grid66 .first-col:before {
  content: "";
  position: absolute;
  left: -15px;
  top: 10px;
  width: 110px;
  height: 1px;
  transform: rotate(28deg);
  background-color: #e8eaec;
}

.my-grid66 .first-col .first-col-top {
  position: absolute;
  right: 4px;
  top: -10px;
}

.my-grid66 .first-col .first-col-bottom {
  position: absolute;
  left: 4px;
  bottom: -10px;
}
</style>
